package com.ellecity06.cwhiskymall.ui.search.history

import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.base.BaseViewModel
import com.ellecity06.common.ktx.addGridDecoration
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.utils.logD
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.adapter.SearchHistoryAdapter
import com.ellecity06.cwhiskymall.databinding.FragmentHistorySearchBinding
import com.ellecity06.cwhiskymall.ui.search.SearchIntent
import com.ellecity06.cwhiskymall.ui.search.SearchState
import com.ellecity06.cwhiskymall.ui.search.SearchViewModel
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent

/**
 * @author ellecity06
 * @time 2024/11/2 10:13
 * @des 搜索历史
 */
class SearchHistoryFragment : BaseMvvmFragment<FragmentHistorySearchBinding, BaseViewModel>(),
    View.OnClickListener {
    override val isLazy: Boolean
        get() = false
    private val historyAdapter: SearchHistoryAdapter by lazy { SearchHistoryAdapter() }
    private lateinit var actViewModel: SearchViewModel

    companion object {
        fun newInstance(): SearchHistoryFragment {
            val bundle = Bundle()
//            bundle.putInt("type", type)
            val fragment = SearchHistoryFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun lazyInit() {
        actViewModel = ViewModelProvider(requireActivity())[SearchViewModel::class.java]
        initEvent()
        initObserver()
        fetchData()
    }

    fun fetchData() {
        lifecycleScope.launchWhenCreated {
            actViewModel.intentChannel.send(SearchIntent.FetchHistory)
        }
    }

    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentHistorySearchBinding {
        return FragmentHistorySearchBinding.inflate(inflater, container, false)
    }

    private fun initObserver() {
        actViewModel.state.observeEvent(requireActivity()) {
            when (it) {
                is SearchState.HistoryList -> {
                    logD("list=${it.list}")
                    historyAdapter.submitList(it.list)
                }
                else -> {}
            }
        }
    }

    private fun initEvent() {
        binding.ivDelete.setOnClickListener(this)
        historyAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) ?: return@setOnItemClickListener
            search(item.name)
        }

    }

    override fun initView() {
        val layoutManager = FlexboxLayoutManager(requireActivity())
        layoutManager.flexDirection = FlexDirection.ROW
        layoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvHistory.layoutManager = layoutManager
        binding.rvHistory.addGridDecoration()
        binding.rvHistory.adapter = historyAdapter
    }

    private fun search(keyword: String) {
        requireActivity().lifecycleScope.launchWhenCreated {
            actViewModel.intentChannel.send(
                SearchIntent.Search(
                    keyword
                )
            )
        }
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            binding.ivDelete.id -> {
                showAlert("删除历史记录",content = "确定删除历史记录吗？") {
                    lifecycleScope.launchWhenCreated {
                        actViewModel.intentChannel.send(SearchIntent.DeleteHistory)
                    }
                }
            }
        }
    }
}